package social.p2p.ui;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import javax.swing.filechooser.FileFilter;
import social.p2p.controller.*;
import social.p2p.model.Foto;
import social.p2p.model.FotoAdvertisement;
import social.p2p.model.NodoFotoAdvertisement;

/**
 *
 * @author cadmilo
 */
public class MainFrame extends javax.swing.JFrame implements Observer {

    private Socialp2pController controller;
    private Foto selectedFoto;

    /**
     * Creates new form MainFrame
     */
    public MainFrame(boolean test) {
        initComponents();
        setLocationRelativeTo(null);
        controller = new Socialp2pController(test);
        controller.addObserver(this);
        controller.init();
        fChooser.setFileFilter(new FileFilter() {

            @Override
            public boolean accept(File file) {
                return file.isDirectory() || file.getName().toLowerCase().endsWith("jpg") || file.getName().toLowerCase().endsWith("jpeg") || file.getName().toLowerCase().endsWith("gif") || file.getName().toLowerCase().endsWith("png");
            }

            @Override
            public String getDescription() {
                return "Imagenes (JPG, GIF, PNG)";
            }
        });
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        fChooser = new javax.swing.JFileChooser();
        jPanel1 = new javax.swing.JPanel();
        lstMostrar = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jScrollPane2 = new javax.swing.JScrollPane();
        pnlImages = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        btnAgregarFoto = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        txtId = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtIdUsuario = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        txtTamanio = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        txtFechaRegistro = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        txtDescargada = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        txtFechaDescarga = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Social P2P");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Fotos Disponibles"));

        lstMostrar.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Todas", "Locales", "Descargadas", "Resultado de Busqueda" }));
        lstMostrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                lstMostrarActionPerformed(evt);
            }
        });

        jLabel2.setText("Mostrar");

        jScrollPane2.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
        jScrollPane2.setViewportView(pnlImages);

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(0, 422, Short.MAX_VALUE)
                .add(jLabel2)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(lstMostrar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 140, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jSeparator1)
                    .add(jScrollPane2)))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lstMostrar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel2))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 227, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel2.setLayout(new javax.swing.BoxLayout(jPanel2, javax.swing.BoxLayout.LINE_AXIS));

        btnAgregarFoto.setIcon(new javax.swing.ImageIcon(getClass().getResource("/social/p2p/ui/img/add.png"))); // NOI18N
        btnAgregarFoto.setText("Agregar Foto");
        btnAgregarFoto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarFotoActionPerformed(evt);
            }
        });
        jPanel2.add(btnAgregarFoto);

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/social/p2p/ui/img/buscar.png"))); // NOI18N
        jButton2.setText("Buscar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton2);

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/social/p2p/ui/img/parecida.png"))); // NOI18N
        jButton3.setText("Fotos Parecidas");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton3);

        jButton5.setText("Iniciar Grabado Estado");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton5);

        jButton6.setText("Recuperar Estado");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton6);

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/social/p2p/ui/img/acerca.png"))); // NOI18N
        jButton4.setText("Acerca de");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton4);

        jPanel3.setBackground(new java.awt.Color(255, 255, 255));
        jPanel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)));
        jPanel3.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N

        jLabel1.setBackground(new java.awt.Color(255, 255, 255));
        jLabel1.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/social/p2p/ui/img/social.png"))); // NOI18N
        jLabel1.setText("Social p2p");

        org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 103, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Información Foto"));

        jLabel3.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
        jLabel3.setText("ID");

        txtId.setText("-");

        jLabel5.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
        jLabel5.setText("ID Usuario");

        txtIdUsuario.setText("-");

        jLabel7.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
        jLabel7.setText("Tamaño(ancho, alto)");

        txtTamanio.setText("-");

        jLabel9.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
        jLabel9.setText("Fecha Registro");

        txtFechaRegistro.setText("-");

        jLabel11.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
        jLabel11.setText("Descargada");

        txtDescargada.setText("-");

        jLabel13.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
        jLabel13.setText("Fecha Descarga");

        txtFechaDescarga.setText("-");

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/social/p2p/ui/img/personas.png"))); // NOI18N
        jButton1.setText("Ver Personas");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel4Layout = new org.jdesktop.layout.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jButton1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jPanel4Layout.createSequentialGroup()
                        .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jLabel3)
                            .add(txtId)
                            .add(jLabel5)
                            .add(txtIdUsuario)
                            .add(jLabel7)
                            .add(txtTamanio)
                            .add(jLabel9)
                            .add(txtFechaRegistro)
                            .add(jLabel11)
                            .add(txtDescargada)
                            .add(jLabel13)
                            .add(txtFechaDescarga))
                        .addContainerGap())))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel4Layout.createSequentialGroup()
                .add(jLabel3)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(txtId)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel5)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(txtIdUsuario)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel7)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(txtTamanio)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel9)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(txtFechaRegistro)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel11)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(txtDescargada)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel13)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(txtFechaDescarga)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(jButton1))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 778, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
            .add(layout.createSequentialGroup()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jPanel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAgregarFotoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarFotoActionPerformed

        final AddDialog addD = new AddDialog(this, true);
        addD.setLocationRelativeTo(this);
        addD.setVisible(true);
        if (addD.id != null && !addD.id.isEmpty()) {
            SwingWorker sw = new SwingWorker() {

                @Override
                protected Object doInBackground() throws Exception {
                    try {
                        controller.addPhoto(addD.id, addD.getPersons(), addD.selectedImage);
                        lstMostrar.setSelectedItem("Locales");
                    } catch (FileNotFoundException ex) {
                        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    ProcessForm.hideIt();
                    return null;
                }
            };
            sw.execute();
            ProcessForm.show("Cargando la Foto");

        }

    }//GEN-LAST:event_btnAgregarFotoActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        /*
         * List<Foto> photos = controller.getPhotos(); for (Foto foto : photos)
         * { PhotoPanel pf = new PhotoPanel(foto, this); pnlImages.add(pf); }
         *
         * pnlImages.updateUI(); jScrollPane2.updateUI();
         */
        SearchDialog sd = new SearchDialog(this, true);
        sd.setLocationRelativeTo(null);
        sd.setVisible(true);
        if (!sd.cancel) {
            String field = null;
            if (sd.field.equals("Identificador")) {
                field = "userId";
            } else if (sd.field.equals("Personas")) {
                field = "personas";
            }
            controller.searchPhotosConEstado(field, sd.searchText);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        JOptionPane.showMessageDialog(this, selectedFoto.getPersonas());
    }//GEN-LAST:event_jButton1ActionPerformed

    private void lstMostrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lstMostrarActionPerformed
        List<Foto> photos = null;
        if (lstMostrar.getSelectedItem().equals("Todas")) {
            photos = controller.getPhotos();
        } else if (lstMostrar.getSelectedItem().equals("Locales")) {
            photos = controller.getLocalPhotos();
        } else if (lstMostrar.getSelectedItem().equals("Descargadas")) {
            photos = controller.getDownloadedPhotos();
        } else {
            return;
        }
        pnlImages.removeAll();
        for (Foto foto : photos) {
            PhotoPanel pf = new PhotoPanel(foto, this);
            pnlImages.add(pf);
        }
        pnlImages.updateUI();
        jScrollPane2.updateUI();
    }//GEN-LAST:event_lstMostrarActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        int rval = fChooser.showOpenDialog(this);
        if (rval == JFileChooser.APPROVE_OPTION) {
            SwingWorker sw = new SwingWorker() {

                @Override
                protected Object doInBackground() throws Exception {
                    File selectedImage = fChooser.getSelectedFile();
                    controller.searchLikeConEstado(selectedImage);
                    return null;
                }
            };
            sw.execute();
            ProcessForm.show("Buscando Fotografías con la misma afinidad");
        }

    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        AboutFrame abf = new AboutFrame();
        abf.setVisible(true);
        abf.setLocationRelativeTo(this);
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        SwingWorker sw = new SwingWorker() {

            @Override
            protected Object doInBackground() throws Exception {
                //for (NodoFotoAdvertisement nodoFotoAdvertisement : searchResult) {
                    //controller.guardarEstadoGlobal(nodoFotoAdvertisement);
                    controller.guardarEstadoGlobal();
                //}
                //lstMostrar.setSelectedItem("Descargadas");    
                //ProcessForm.hideIt();
                return null;
            }
        };
        sw.execute();
        //ProcessForm.show("Grabando el estado global del sistema");
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        SwingWorker sw = new SwingWorker() {

            @Override
            protected Object doInBackground() throws Exception {
                //for (NodoFotoAdvertisement nodoFotoAdvertisement : searchResult) {
                    //controller.guardarEstadoGlobal(nodoFotoAdvertisement);
                    controller.recuperarEstadoGlobal();
                //}
                //lstMostrar.setSelectedItem("Descargadas");    
                //ProcessForm.hideIt();
                return null;
            }
        };
        sw.execute();
        //ProcessForm.show("Recuperando el estado global del sistema");
    }//GEN-LAST:event_jButton6ActionPerformed

    public void setSelectedFoto(Foto selectedFoto) {
        this.selectedFoto = selectedFoto;
        txtId.setText(selectedFoto.getId());
        txtIdUsuario.setText(selectedFoto.getUserId());
        txtTamanio.setText(selectedFoto.getAncho() + "," + selectedFoto.getAlto());
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
        if (selectedFoto.getTiempoRegistro() != null) {
            int offset = (selectedFoto.getUtcRegistro() / 1000) / 3600;
            txtFechaRegistro.setText(sdf.format(selectedFoto.getTiempoRegistro()) + "(GTM" + offset + ")");
        }
        if (selectedFoto.getTiempoDescarga() != null) {
            int offset = (selectedFoto.getUtcDescarga() / 1000) / 3600;
            txtFechaDescarga.setText(sdf.format(selectedFoto.getTiempoDescarga()) + "(GTM" + offset + ")");
        }
        txtDescargada.setText((selectedFoto.isDescargada() ? "SI" : "NO"));
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                int resp = JOptionPane.showConfirmDialog(null, "Desea iniciar un cliente de prueba", "Inicio", JOptionPane.YES_NO_OPTION);
                if (resp == JOptionPane.YES_OPTION) {
                    new MainFrame(true).setVisible(true);
                } else {
                    new MainFrame(false).setVisible(true);
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregarFoto;
    private javax.swing.JFileChooser fChooser;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JComboBox lstMostrar;
    private javax.swing.JPanel pnlImages;
    private javax.swing.JLabel txtDescargada;
    private javax.swing.JLabel txtFechaDescarga;
    private javax.swing.JLabel txtFechaRegistro;
    private javax.swing.JLabel txtId;
    private javax.swing.JLabel txtIdUsuario;
    private javax.swing.JLabel txtTamanio;
    // End of variables declaration//GEN-END:variables
    private ArrayList<FotoAdvertisement> searchResult;
    private SearchEvent lastSearchEvent;

    @Override
    public void update(Observable o, Object o1) {
        if (o1 instanceof SearchEvent) {
            SearchEvent se = (SearchEvent) o1;
            if (lastSearchEvent == null || lastSearchEvent.getSearchId() != se.getSearchId()) {
                searchResult = new ArrayList<FotoAdvertisement>();
                pnlImages.removeAll();
            }
            searchResult.addAll(se.getResult());
            for (FotoAdvertisement fotoAdvertisement : se.getResult()) {
                Foto f = AdvertisementManager.getFoto(fotoAdvertisement);
                PhotoPanel pf = new PhotoPanel(f, this);
                pnlImages.add(pf);
            }
            lstMostrar.setSelectedItem("Resultado de Busqueda");
            lastSearchEvent = se;
        } else if (o1 instanceof UpdateListEvent) {
            UpdateListEvent ul = (UpdateListEvent) o1;
            pnlImages.removeAll();
            for (Foto foto : ul.getFotos()) {
                PhotoPanel pf = new PhotoPanel(foto, this);
                pnlImages.add(pf);
            }
            lstMostrar.setSelectedItem(ul.getSelectedOption());
        } else if (o1 instanceof SearchLikeEvent) {
            SearchLikeEvent se = (SearchLikeEvent) o1;
            JOptionPane.showMessageDialog(this, "Se ha descargado la foto:" + se.fotoAdvertisement.getUserId() + "\n" + se.fotoAdvertisement.getId());
            lstMostrar.setSelectedItem("Descargadas");
        }
        try {
            pnlImages.updateUI();
        } catch (Exception ex) {
        }
        try {
            jScrollPane2.updateUI();
        } catch (Exception ex) {
        }
    }

    public void downloadFoto(final String userId) {
        SwingWorker sw = new SwingWorker() {

            @Override
            protected Object doInBackground() throws Exception {
                for (FotoAdvertisement fotoAdvertisement : searchResult) {
                    if (fotoAdvertisement.getUserId().equals(userId)) {
                        controller.downloadFotoConEstado(fotoAdvertisement);
                    }
                }
                lstMostrar.setSelectedItem("Descargadas");
                ProcessForm.hideIt();
                return null;
            }
        };
        sw.execute();
        ProcessForm.show("Descargando la fotografía");
    }
}
